const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");
const fs = require("fs");

// Image upload configuration
const imageStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/images/"); // Make sure this directory exists
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname));
  },
});

const uploadImage = multer({
  storage: imageStorage,
  limits: {
    fileSize: 20 * 1024 * 1024, // Limit file size to 20MB
  },
}).single("file"); // 'file' should match the first parameter in frontend formData.append

router.post("/upload/img", (req, res) => {
  uploadImage(req, res, function (err) {
    if (err) {
      return res.status(500).json({
        code: 500,
        message: "上传失败",
        error: err.message,
      });
    }

    // Upload successful
    res.json({
      code: 200,
      message: "上传成功",
      data: {
        img: `/public/images/${req.file.filename}`,
        fileUrl: `${process.env.BASE_URL}/public/images/${req.file.filename}`,
      },
    });
  });
});

router.post("/upload/video", (req, res) => {
  const uploadDir = "public/video";
  if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
  }

  const videoStorage = multer.diskStorage({
    destination: (req, file, cb) => cb(null, uploadDir),
    filename: (req, file, cb) => {
      const uniqueName = `${Date.now()}-${Math.round(Math.random() * 1e9)}${path.extname(file.originalname)}`;
      cb(null, uniqueName);
    }
  });

  // 关键修改：确保这里的字段名与前端的字段名一致
  const uploadVideo = multer({
    storage: videoStorage,
    limits: { fileSize: 2000 * 1024 * 1024 },
    fileFilter: (req, file, cb) => {
      const allowedTypes = /mp4|mov|avi|mkv|webm/;
      const extValid = allowedTypes.test(path.extname(file.originalname).toLowerCase());
      const mimeValid = allowedTypes.test(file.mimetype);
      extValid && mimeValid ? cb(null, true) : cb(new Error("只允许上传视频文件 (mp4, mov, avi, mkv, webm)"), false);
    }
  }).single('file'); // ⚠️ 必须与前端的字段名一致

  uploadVideo(req, res, (err) => {
    if (err) {
      console.error("上传错误:", err);
      return res.status(500).json({
        code: 500,
        message: "视频上传失败",
        error: err.message.includes("Unexpected field") 
          ? "请检查上传字段名是否为 'video'" 
          : err.message
      });
    }

    if (!req.file) {
      return res.status(400).json({
        code: 400,
        message: "未上传视频文件或格式无效"
      });
    }

    res.json({
      code: 200,
      message: "视频上传成功",
      data: {
        path: `/public/video/${req.file.filename}`,
        fileUrl: `${process.env.BASE_URL || "http://localhost:3000"}/public/video/${req.file.filename}`,
        size: req.file.size,
        type: req.file.mimetype
      }
    });
  });
});

module.exports = router;
